package com.ziyun.erp.modules.order.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.service.order.api.OrderService;
import com.service.order.constant.OrderResult;
import com.service.order.model.order.OrderCancelBatchParamDto;
import com.utility.New;
import com.ziyun.erp.common.e.DeleteEnum;
import com.ziyun.erp.common.e.goods.GoodsTypeEnum;
import com.ziyun.erp.common.e.member.UserTypeEnum;
import com.ziyun.erp.common.e.order.*;
import com.ziyun.erp.common.e.production.OrderProductionStatusEnum;
import com.ziyun.erp.common.utils.ErpOrderUtils;
import com.ziyun.erp.common.utils.JsonUtils;
import com.ziyun.erp.common.utils.UserUtils;
import com.ziyun.erp.modules.finance.entity.FinanceReceiptsAccountEntity;
import com.ziyun.erp.modules.finance.service.FinanceReceiptsAccountService;
import com.ziyun.erp.modules.logistics.dto.ErpLogisticsDto;
import com.ziyun.erp.modules.logistics.entity.ErpLogisticsEntity;
import com.ziyun.erp.modules.logistics.entity.ErpLogisticsItemEntity;
import com.ziyun.erp.modules.logistics.service.ErpLogisticsItemService;
import com.ziyun.erp.modules.logistics.service.ErpLogisticsService;
import com.ziyun.erp.modules.logistics.service.LogisticsTypeService;
import com.ziyun.erp.modules.member.entity.UserBaseInfoEntity;
import com.ziyun.erp.modules.member.entity.UserCreditEntity;
import com.ziyun.erp.modules.member.entity.UserWalletEntity;
import com.ziyun.erp.modules.member.service.UserBaseInfoService;
import com.ziyun.erp.modules.member.service.UserCreditService;
import com.ziyun.erp.modules.member.service.UserWalletService;
import com.ziyun.erp.modules.order.dao.OrderInfoDao;
import com.ziyun.erp.modules.order.dto.OrderPaymentDto;
import com.ziyun.erp.modules.order.dto.PaperItemAuditDto;
import com.ziyun.erp.modules.order.entity.*;
import com.ziyun.erp.modules.order.service.*;
import com.ziyun.erp.modules.order.utils.UserPaymentUtils;
import com.ziyun.erp.modules.order.vo.*;
import com.ziyun.erp.modules.production.entity.ErpOrderItemEntity;
import com.ziyun.erp.modules.production.entity.ErpOrderProductionEntity;
import com.ziyun.erp.modules.production.service.ErpOrderItemService;
import com.ziyun.erp.modules.production.service.ErpOrderProductionService;
import io.renren.common.exception.RRException;
import io.renren.common.utils.*;
import io.renren.modules.sys.service.MailService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("orderInfoService")
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoDao, OrderInfoEntity> implements OrderInfoService {

    /**
     * 日志
     */
    private  static Logger logger = LoggerFactory.getLogger(OrderInfoServiceImpl.class);

    @Autowired
    private UserPaymentBillService userPaymentBillService;
    @Autowired
    private OrderRemarksService orderRemarksService;
    @Autowired
    private UserPaymentService userPaymentService;
    @Autowired
    private OrderLogService orderLogService;
    @Autowired
    private ErpOrderService erpOrderService;
    @Autowired
    private ErpOrderItemService erpOrderItemService;
    @Autowired
    private ErpOrderLogService erpOrderLogService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private UserBaseInfoService userBaseInfoService;
    @Autowired
    private FinanceReceiptsAccountService financeReceiptsAccountService;
    @Autowired
    private ErpOrderProductionService erpOrderProductionService;
    @Autowired
    private LogisticsTypeService logisticsTypeService;
    @Autowired
    private ErpLogisticsService erpLogisticsService;
    @Autowired
    private ErpLogisticsItemService erpLogisticsItemService;
    @Autowired
    private ErpOrderAllotRelevanceService erpOrderAllotRelevanceService;
    @Autowired
    private OrderLogisticsService orderLogisticsService;
    @Autowired
    private MailService mailService;
    @Autowired
    private OrderService microOrderService;
    @Autowired
    private UserWalletService userWalletService;
    @Autowired
    private UserCreditService usercreditService;

    public R queryPageOrderList(Map<String, Object> params) {
        int totalCount = this.baseMapper.countOrder(params);

        int current = Integer.valueOf((String)params.get("page"));
        int size = Integer.valueOf((String)params.get("limit"));
        params.put("offset", (current - 1) * size);
        params.put("limit", size);
        List<OrderInfoVo> list = this.baseMapper.queryPageOrderList(params);

        // 存放枚举类到userdata
        Map<String,Object> mapEnum = new HashMap<>();
        mapEnum.put("orderInfoStatusEnum", JsonUtils.enumToList(OrderInfoStatusEnum.class));

        R r = R.ok();
        r.put("page", new PageUtils(list, totalCount, size, current));
        r.put("userData", mapEnum);
        return r;
    }

    public PageUtils queryPagePaperOrderList(Map<String, Object> params) {
        // 紫云网订单
        params.put("supplierId", 1);
        // 大纸类型订单
        params.put("promotionType", PromotionTypeEnum.PAPER.toCode());

        int totalCount = this.baseMapper.countOrder(params);

        int current = Integer.valueOf((String)params.get("page"));
        int size = Integer.valueOf((String)params.get("limit"));
        params.put("offset", (current - 1) * size);
        params.put("limit", size);
        List<OrderInfoVo> list = this.baseMapper.queryPagePaperOrderList(params);

        return new PageUtils(list, totalCount, size, current);
    }

    @Override
    public Page<OrderInfoEntity> selectNotSynZiyunOrderPage(Page<OrderInfoEntity> page, String startTime) {
        List<OrderInfoEntity> list = baseMapper.selectNotSynZiyunOrderList(page, startTime);
        return page.setRecords(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean orderPay(OrderInfoEntity orderInfo, UserPaymentEntity userPayment, UserPaymentBillEntity userPaymentBill) {
        String orderId = orderInfo.getOrderId();
        // 更新订单信息
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("payStatus", orderInfo.getPayStatus());
        updateMap.put("payed", orderInfo.getPayed());
        this.baseMapper.updateByMap(orderId, updateMap);

        // 更新内部订单信息
        updateMap.put("paymentTime", DateUtils.format(userPayment.getTPayed(), "yyyy-MM-dd HH:mm:ss"));
        updateMap.put("payment", userPayment.getPayName());
        erpOrderService.updateByMap(updateMap, orderId);

        // 新增用户支付记录表信息
        userPaymentService.insert(userPayment);
        // 新增用户支付关联表信息
        userPaymentBillService.insert(userPaymentBill);

        return true;
    }

    /**
     * 根据会员ID查询订单
     * @param memberId
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params, Integer memberId) {
        Page<OrderInfoEntity> page=this.selectPage(
                new Query<OrderInfoEntity>(params).getPage(),
                new EntityWrapper<OrderInfoEntity>().eq("user_id",memberId)
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean orderDiscountAudit(OrderInfoEntity orderInfo, OrderRemarksEntity orderRemarksEntity, String orderNo) {
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("discount", orderInfo.getDiscount());
        updateMap.put("payableAmount", orderInfo.getPayableAmount());
        updateMap.put("payStatus", orderInfo.getPayStatus());
        this.baseMapper.updateByMap(orderInfo.getOrderId(), updateMap);

        if (orderNo != null){
            erpOrderService.updateByMap(updateMap, orderNo);
        }

        orderRemarksService.insert(orderRemarksEntity);

        return true;
    }

    /**
     * 查询展示订单
     * @param orderId 订单号
     * @return
     */
    @Override
    public OrderInfoVo selectOrderInfoVoById(Long orderId) {
        return this.baseMapper.selectOrderInfoVoById(orderId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean orderInvalid(String orderId, String orderNo) {
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("status", OrderInfoStatusEnum.DEAD.toCode());
        this.baseMapper.updateByMap(orderId, updateMap);

        if (orderNo != null){
            updateMap.clear();
            updateMap.put("productionStatus", ProductionStatusEnum.CANCELLED.toInt());
            erpOrderService.updateByMap(updateMap, orderNo);
        }

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean orderFinish(String orderId, String orderNo) {
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("status", OrderInfoStatusEnum.FINISH.toCode());
        updateMap.put("receivedTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        this.baseMapper.updateByMap(orderId, updateMap);

        if (orderNo != null){
            updateMap.clear();
            updateMap.put("productionStatus", ProductionStatusEnum.FINISH.toInt());
            erpOrderService.updateByMap(updateMap, orderNo);
        }

        return true;
    }

    /**
     * 查询 紫云网未支付订单
     * @param day           未支付天数
     * @param promotionType 订单类型
     * @return
     */
    @Override
    public List<OrderInfoEntity> selectNotPayZiyunOrderPage(Integer day, String promotionType) {
        List<OrderInfoEntity> list = baseMapper.selectNotPayZiyunOrderPage(day,promotionType);
        return list;
    }

    /**
     * 同步 紫云网订单支付信息;查询所有已同步订单，支付信息变更的订单
     * @param page
     * @return
     */
    @Override
    public Page<OrderInfoEntity> selectPayChangeZiyunOrderPage(Page<OrderInfoEntity> page) {
        List<OrderInfoEntity> list = baseMapper.selectPayChangeZiyunOrderPage(page);
        return page.setRecords(list);
    }

    @Override
    public Page<OrderInfoEntity> selectReceiveChangeZiyunOrderPage(Page<OrderInfoEntity> page) {
        List<OrderInfoEntity> list = baseMapper.selectReceiveChangeZiyunOrderPage(page);
        return page.setRecords(list);
    }

    @Override
    public Page<OrderInfoEntity> selectCancleChangeZiyunOrderPage(Page<OrderInfoEntity> page) {
        List<OrderInfoEntity> list = baseMapper.selectCancleChangeZiyunOrderPage(page);
        return page.setRecords(list);
    }

    /**
     * 取消紫云网订单
     * @param orderInfoList
     */
    @Override
    public String cancelZiyunOrder(List<OrderInfoEntity> orderInfoList) {
        StringBuilder orderIds = new StringBuilder();
        for(OrderInfoEntity orderInfoEntity : orderInfoList){
            // 线上分配订单，不取消
            List<ErpOrderAllotRelevanceEntity> erpOrderAllotRelevanceEntityList = erpOrderAllotRelevanceService.selectList(
                    new EntityWrapper<ErpOrderAllotRelevanceEntity>()
                            .eq("order_allot_no", orderInfoEntity.getOrderId())
            );
            if(erpOrderAllotRelevanceEntityList != null && erpOrderAllotRelevanceEntityList.size() >= 1){
                String log = "分配订单：" + orderInfoEntity.getOrderId() + "，取消失败";
                logger.info(log);
                continue;
            }

            // 查询订单支付信息
            OrderInfoEntity checkOrder = this.selectById(orderInfoEntity.getOrderId());
            if("1".equals(checkOrder.getPayStatus()) || !"active".equals(orderInfoEntity.getStatus())){
                continue;
            }
            UserPaymentEntity userPaymentEntity = userPaymentService.getPaySuccLastEntityByOrderId(orderInfoEntity.getOrderId());
            if(userPaymentEntity != null){
                String log = "订单：" + orderInfoEntity.getOrderId() + "已支付，取消失败";
                logger.info(log);
                continue;
            }

            // 取消erp订单
            ErpOrderEntity erpOrderEntity = erpOrderService.selectByOrderId(Long.parseLong(orderInfoEntity.getOrderId()));
            if(erpOrderEntity != null){
                Map<String,Object> upMap = new HashMap<>();
                upMap.put("productionStatus", ProductionStatusEnum.CANCELLED.toInt());
                erpOrderService.updateByMap(upMap, erpOrderEntity.getOrderNo());
                // 订单日志
                erpOrderLogService.insertOrderLog(erpOrderEntity.getOrderNo(),"未支付订单自动取消");
            }
            orderIds.append("," + orderInfoEntity.getOrderId());
        }
        return orderIds.toString().substring(1,orderIds.toString().length());
    }

    /**
     * 紫云网订单自动确认完成
     * @param orderInfoEntityList
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void finishZiyunOrder(List<OrderInfoEntity> orderInfoEntityList) {
        for (OrderInfoEntity orderInfoEntity:orderInfoEntityList){
            if ("finish".equals(orderInfoEntity.getStatus()))
                continue;

            // 线上分配订单，不自动确认完成
            List<ErpOrderAllotRelevanceEntity> erpOrderAllotRelevanceEntityList = erpOrderAllotRelevanceService.selectList(
                    new EntityWrapper<ErpOrderAllotRelevanceEntity>()
                            .eq("order_allot_no", orderInfoEntity.getOrderId())
            );
            if(erpOrderAllotRelevanceEntityList != null && erpOrderAllotRelevanceEntityList.size() >= 1){
                String log = "分配订单：" + orderInfoEntity.getOrderId() + "，不自动确认完成";
                logger.info(log);
                continue;
            }
            // 查询支付信息
            UserPaymentEntity payInfo = userPaymentService.getPaySuccLastEntityByOrderId(orderInfoEntity.getOrderId());
            if(payInfo == null){
                logger.info("订单未支付，不允许确认收货！");
                continue;
            }

            Map<String,Object> erpOrderMap = new HashMap<>();
            erpOrderMap.put("productionStatus",ProductionStatusEnum.FINISH.toInt());
            erpOrderMap.put("receivedStatus",1); // 已收货
            erpOrderMap.put("receivedTime",new Date());
            erpOrderService.updateByMap(erpOrderMap,orderInfoEntity.getOrderId());
            erpOrderLogService.insertOrderLog(orderInfoEntity.getOrderId(),"系统自动确认订单完成");

            // 商城订单操作
            Map<String,Object> orderMap = new HashMap<>();
            orderMap.put("status", OrderInfoStatusEnum.FINISH.toCode());
            orderMap.put("receivedStatus",1); // 已收货
            SimpleDateFormat f= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            orderMap.put("receivedTime",f.format(new Date()));
            baseMapper.updateByMap(orderInfoEntity.getOrderId(),orderMap);

            // 发起紫云网完成事件
//            OrderMessageEvent event = new OrderMessageEvent(this, Long.valueOf(orderInfoEntity.getUserId()), orderInfoEntity.getOrderId(), "receive");
//            EventBusPusher.syncPost(event);

            OrderLogEntity orderLogEntity = new OrderLogEntity();
            orderLogEntity.setOrderId(Long.parseLong(orderInfoEntity.getOrderId()));
            orderLogEntity.setOpId(1);
            orderLogEntity.setOpName("admin");
            orderLogEntity.setBillType("order");
            orderLogEntity.setBehavior("receive");
            orderLogEntity.setResult("SUCCESS");
            orderLogEntity.setLogText("自动确认收货");
            orderLogService.insert(orderLogEntity);
        }
    }

    @Override
    public R queryPageMallOrderList(Map<String, Object> params) {
        // 默认查询活动订单
        String status = (String) params.get("status");
        if (status == null){
            params.put("status", OrderInfoStatusEnum.ACTIVE.toCode());
        }
        int totalCount = this.baseMapper.countOrder(params);

        int current = Integer.valueOf((String)params.get("page"));
        int size = Integer.valueOf((String)params.get("limit"));
        params.put("offset", (current - 1) * size);
        params.put("limit", size);
        List<OrderInfoVo> list = this.baseMapper.queryPageMallOrderList(params);

        // 存放枚举类到userdata
        Map<String, List> mapEnum = new HashMap<>();
        mapEnum.put("payTypeEnum", JsonUtils.enumToList(PayTypeEnum.class));
        mapEnum.put("orderInfoStatusEnum", JsonUtils.enumToList(OrderInfoStatusEnum.class));
        mapEnum.put("thirdMerchantTypeEnum", JsonUtils.enumToList(ThirdMerchantTypeEnum.class));

        R r = R.ok();
        r.put("page", new PageUtils(list, totalCount, size, current));
        r.put("userData", mapEnum);
        return r;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R paperAudit(Map<String, Object> params, Long userId, String username) {
        String orderInfo = (String) params.get("orderInfo");
        OrderInfoEntity orderInfoAudit = JsonUtils.getJsonToObject(orderInfo, OrderInfoEntity.class);
        String orderId = orderInfoAudit.getOrderId();
        OrderInfoEntity orderInfoEntity = this.baseMapper.selectById(orderId);
        if (orderInfoEntity == null){
            return R.error("未查询到订单信息！");
        }
        if (!StringUtils.equals(orderInfoEntity.getPromotionType(), PromotionTypeEnum.PAPER.toCode())){
            return R.error("非大纸订单，审核失败！");
        }
        if (!StringUtils.equals(orderInfoEntity.getPayStatus(), PayStatusEnum.PAPER_WAIT_AUDIT_6.toCode())
                || !StringUtils.equals(orderInfoEntity.getStatus(), OrderInfoStatusEnum.ACTIVE.toCode())){
            return R.error("订单状态异常，审核失败！");
        }

        BigDecimal costFreight = orderInfoAudit.getCostFreight();
        BigDecimal discount = orderInfoAudit.getDiscount();
        BigDecimal payableAmount = orderInfoAudit.getPayableAmount();
        Map<String, Object> updateMap = new HashMap<>();
        if (costFreight != null){
            updateMap.put("costFreight", costFreight);
        }else {
            costFreight = BigDecimal.ZERO;
        }
        if (discount != null){
            updateMap.put("discount", discount);
        }else {
            discount = BigDecimal.ZERO;
        }
        BigDecimal totalAmount = payableAmount.subtract(costFreight.add(discount));

        updateMap.put("payableAmount", payableAmount);
        updateMap.put("totalAmount", totalAmount);
        updateMap.put("payStatus", PayStatusEnum.NOT_PAY_0.toCode());
        this.baseMapper.updateByMap(orderId, updateMap);

        ErpOrderEntity erpOrderEntity = erpOrderService.selectByOrderId(Long.valueOf(orderId));
        if (erpOrderEntity == null){
            erpOrderEntity = ErpOrderUtils.ziyunOrderToErp(orderInfoEntity);
            erpOrderEntity.setAuditName(userId.toString());
            erpOrderEntity.setAuditTime(new Date());
            erpOrderEntity.setProductionStatus(ProductionStatusEnum.UN_ALLOT.toInt());
            erpOrderService.insert(erpOrderEntity);
        }else {
            updateMap.put("auditName", userId.toString());
            updateMap.put("auditTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            updateMap.put("productionStatus", ProductionStatusEnum.UN_ALLOT.toInt());
            erpOrderService.updateByMap(updateMap, orderId);
        }

        String orderItem = (String) params.get("orderItem");
        if (StringUtil.isNotEmpty(orderItem)){
            List<OrderItemEntity> orderItemList = (List<OrderItemEntity>) JsonUtils.queryJsonToList(orderItem, OrderItemEntity.class);
            if (orderItemList != null && orderItemList.size() > 0){
                updateMap.clear();
                for (OrderItemEntity entity : orderItemList){
                    updateMap.put("price", entity.getPrice());
                    updateMap.put("amount", entity.getAmount());
                    updateMap.put("nums", entity.getNums());
                    orderItemService.updateByMap(updateMap, entity.getItemId());
                }
            }
        }

        String remark = (String) params.get("remark");
        if (StringUtil.isNotEmpty(remark)){
            OrderRemarksEntity orderRemarks = new OrderRemarksEntity();
            orderRemarks.setOrOrderId(Long.valueOf(orderId));
            orderRemarks.setOrRemarks(remark);
            orderRemarks.setOrCreateName(username);
            orderRemarksService.insert(orderRemarks);
        }

        // 订单日志
        erpOrderLogService.insertOrderLog(erpOrderEntity.getOrderNo(),"大纸订单审核");

        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R paperOrderAudit(PaperItemAuditDto paperItemAuditDto, Long userId, String username) {
        String orderId = paperItemAuditDto.getOrderId();
        OrderInfoEntity orderInfoEntity = this.baseMapper.selectById(orderId);
        if (orderInfoEntity == null){
            return R.error("未查询到订单信息！");
        }
        if (!StringUtils.equals(orderInfoEntity.getPromotionType(), PromotionTypeEnum.PAPER.toCode())){
            return R.error("非大纸订单，审核失败！");
        }
        if (!StringUtils.equals(orderInfoEntity.getPayStatus(), PayStatusEnum.PAPER_WAIT_AUDIT_6.toCode())
                || !StringUtils.equals(orderInfoEntity.getStatus(), OrderInfoStatusEnum.ACTIVE.toCode())){
            return R.error("订单状态异常，审核失败！");
        }
        BigDecimal costFreight = paperItemAuditDto.getCostFreight();
        BigDecimal discount = paperItemAuditDto.getDiscount();
        BigDecimal payableAmount = paperItemAuditDto.getPayableAmount();
        Map<String, Object> updateMap = new HashMap<>();
        if (costFreight != null){
            updateMap.put("costFreight", costFreight);
        }else {
            costFreight = BigDecimal.ZERO;
        }
        if (discount != null){
            updateMap.put("discount", discount);
        }else {
            discount = BigDecimal.ZERO;
        }
        BigDecimal totalAmount = payableAmount.subtract(costFreight.add(discount));
        updateMap.put("payableAmount", payableAmount);
        updateMap.put("totalAmount", totalAmount);
        updateMap.put("payStatus", PayStatusEnum.NOT_PAY_0.toCode());
        this.baseMapper.updateByMap(orderId, updateMap);

        ErpOrderEntity erpOrderEntity = erpOrderService.selectById(orderId);
        if (erpOrderEntity == null){
            OrderInfoEntity orderInfo = this.selectById(orderId);
            erpOrderEntity = ErpOrderUtils.ziyunOrderToErp(orderInfo);
            erpOrderEntity.setAuditName(userId.toString());
            erpOrderEntity.setAuditTime(new Date());
            erpOrderEntity.setProductionStatus(ProductionStatusEnum.UN_ALLOT.toInt());
            erpOrderService.insert(erpOrderEntity);
            List<OrderItemEntity> orderItemEntityList = orderItemService.selectByOrderId(Long.valueOf(orderId));
            List<ErpOrderItemEntity> erpOrderItemEntityList = ErpOrderUtils.ziyunOrderItemToErp(orderItemEntityList, orderId);
            erpOrderItemService.insertBatch(erpOrderItemEntityList);
        }else {
            updateMap.put("auditName", userId);
            updateMap.put("auditTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            updateMap.put("productionStatus", ProductionStatusEnum.UN_ALLOT.toInt());
            erpOrderService.updateByMap(updateMap, orderId);
        }

        List<OrderItemEntity> orderItemList = paperItemAuditDto.getOrderItemList();
        if (orderItemList != null && orderItemList.size() > 0){
            updateMap.clear();
            List<Integer> itemIds = new ArrayList<>();
            for (OrderItemEntity entity : orderItemList){
                Integer itemId = entity.getItemId();
                updateMap.put("price", entity.getPrice());
                updateMap.put("amount", entity.getAmount());
                updateMap.put("nums", entity.getNums());
                orderItemService.updateByMap(updateMap, itemId);
                itemIds.clear();
                itemIds.add(itemId);
                erpOrderItemService.updateBatchByOrderItemId(updateMap, itemIds);
            }
        }

        String remark = paperItemAuditDto.getRemark();
        if (StringUtil.isNotEmpty(remark)){
            OrderRemarksEntity orderRemarks = new OrderRemarksEntity();
            orderRemarks.setOrOrderId(Long.valueOf(orderId));
            orderRemarks.setOrRemarks(remark);
            orderRemarks.setOrCreateName(username);
            orderRemarksService.insert(orderRemarks);
        }

        // 订单日志
        erpOrderLogService.insertOrderLog(orderId,"大纸订单审核");

        return R.ok();
    }

    @Override
    public void updateFinishStatus(List<String> orderIds) {
        baseMapper.updateFinishStatus(orderIds);
    }

    @Override
    public Page<OrderInfoEntity> selectNotSendConfirmPage(Page<OrderInfoEntity> page) {
        List<OrderInfoEntity> list = baseMapper.selectNotSendConfirmPage(page);
        return page.setRecords(list);
    }

    @Override
    public  List<OrderInfoEntity>  selectNotProductOrderList(Integer sellerId,String datetime) {
      return baseMapper.selectNotProductOrderList(sellerId,datetime);
    }

    @Override
    public R sendLogisticsInfo(String orderId) {
        R re = R.ok();
        ErpOrderEntity erpOrder = erpOrderService.selectById(orderId);
        if (erpOrder == null){
            OrderInfoVo orderInfo = this.selectOrderInfoVoById(Long.valueOf(orderId));
            erpOrder = new ErpOrderEntity();
            erpOrder.setShipName(orderInfo.getShipName());
            erpOrder.setShipMobile(orderInfo.getShipMobile());
            erpOrder.setShipTel(orderInfo.getShipTel());
            erpOrder.setShipAddr(orderInfo.getShipAddr());
            erpOrder.setShipArea(orderInfo.getShipArea());
            erpOrder.setShipAreaId(orderInfo.getShipAreaId());
            erpOrder.setThirdMerchantId(orderInfo.getSupplierId());
            erpOrder.setTotalAmount(orderInfo.getTotalAmount());
            erpOrder.setSendType(orderInfo.getPickUp() == true ? 1 : 0);
            erpOrder.setOrderNo(orderId);
            erpOrder.setMemberName(orderInfo.getMemberName());
        }
        re.put("erpOrder", erpOrder);

        // 商品列表
        List<OrderItemEntity> orderItemEntityList = orderItemService.selectByOrderId(Long.valueOf(orderId));
        re.put("orderItemEntityList", orderItemEntityList);

        // 物流类型
        List<Map<Integer,String>> logisticsTypeList = logisticsTypeService.queryTypeList();
        re.put("logisticsTypeList", logisticsTypeList);

        return re;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveOrderLogisticsInfo(ErpLogisticsDto erpLogisticsDto, String createName) {
        ErpLogisticsEntity erpLogistics = erpLogisticsDto.getErpLogisticsEntity();
        Long orderId = erpLogistics.getOrderId();
        ErpOrderEntity erpOrder = erpOrderService.selectById(orderId);
        if (erpOrder == null || erpOrder.getProductionStatus() == ProductionStatusEnum.UN_AUDITED.toInt()){
            return R.error("订单未审核");
        }

        Integer logiType = erpLogistics.getLogiType();
        Date currDate = new Date();
        // 添加物流信息
        erpLogistics.setCreateName(createName);
        erpLogistics.setSendTime(new Date());
        erpLogisticsService.insert(erpLogistics);
        List<ErpLogisticsItemEntity> erpLogisticsItemList = erpLogisticsDto.getErpLogisticsItemList();
        int itemListSize = erpLogisticsItemList.size();
        if (itemListSize > 0){
            erpLogisticsItemService.saveBatchByLogisticsId(erpLogisticsItemList, erpLogistics.getLogiId());
        }

        Integer shipStatus = erpOrder.getShipStatus();
        if (shipStatus.intValue() == ShipStatusEnum.NOT_SHIPPED.toInt()){
            Map<String, Object> updateMap = new HashMap<>();
            updateMap.put("shipStatus", ShipStatusEnum.shipped.toCode());
            updateMap.put("sendTime", DateUtils.format(currDate, "yyyy-MM-dd HH:mm:ss"));
            if (logiType.intValue() == 3){// 自提
                updateMap.put("deliveryTime", DateUtils.format(currDate, "yyyy-MM-dd HH:mm:ss"));
            }else {// 非自提，默认7天确认收货
                updateMap.put("deliveryTime", DateUtils.format(DateUtils.addDateDays(currDate, 7), "yyyy-MM-dd HH:mm:ss"));
            }
            erpOrderService.updateByMap(updateMap, orderId.toString());

            updateMap.clear();
            updateMap.put("shipStatus", ShipStatusEnum.shipped.toCode());
            this.updateByMap(updateMap, orderId.toString());
        }

        erpOrderLogService.insertOrderLog(orderId.toString(),"大纸订单添加物流");

        return R.ok();
    }

    @Override
    public List<OrderBonusVo> selectSellerOrderList() {
        return this.baseMapper.selectSellerOrderList();
    }

    @Override
    public boolean updateByMap(Map<String, Object> map, String orderId) {
        int update = this.baseMapper.updateByMap(orderId, map);
        if (update > 0){
            return true;
        }
        return false;
    }

    @Override
    public String getOrderId() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMddHHmm");
        String orderIdStr = "9" + dateFormat.format(new Date()) + (int) (new Random().nextInt(89999) + 10000);
        return orderIdStr;
    }

    @Override
    public void saveAllotMerchantOrder(OrderInfoEntity orderInfo, List<OrderItemEntity> orderItemList) {
        this.insert(orderInfo);
        orderItemService.insertBatch(orderItemList);
    }

    @Override
    public R orderRemarks(String orderId, String remarks, String userName) {
        OrderRemarksEntity ore = new OrderRemarksEntity();
        ore.setOrOrderId(Long.valueOf(orderId));
        ore.setOrRemarks(remarks);
        ore.setOrCreateName(userName);
        orderRemarksService.insert(ore);
        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R orderInfoInvalid(String orderId, String remarks, String username) {
        OrderInfoEntity orderInfo = this.selectById(orderId);
        String status = orderInfo.getStatus();
        if (!StringUtils.equals(status, OrderInfoStatusEnum.ACTIVE.toCode())){
            return R.error("订单状态异常！");
        }
        String payStatus = orderInfo.getPayStatus();
        if (StringUtils.equals(payStatus, PayStatusEnum.ALREADY_PAY_1.toCode())){
            return R.error("订单已支付！");
        }

        try {
            logger.info("================= order cancel api start==================");
            Set<String> orderIds = New.hashSet(1);
            orderIds.add(orderId);
            OrderCancelBatchParamDto orderCancelBatchParamDto = OrderCancelBatchParamDto.builder()
                    .orderIds(orderIds)
                    .userId(Long.valueOf(orderInfo.getUserId()))
                    .build();
            logger.info("================= order cancel api param：{}", JsonUtils.object2String(orderCancelBatchParamDto));
            OrderResult<?> orderResult = microOrderService.updateOrderCancelBatch(orderCancelBatchParamDto);
            int code = orderResult.getCode();
            if (code != 1){
                return R.error(orderResult.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException("服务异常，请稍后重试！");
        }

        // 订单状态
        ErpOrderEntity erpOrder = erpOrderService.selectById(orderId);
        if (erpOrder != null){
            Map<String, Object> updateMap = new HashMap<>();
            updateMap.put("productionStatus", ProductionStatusEnum.CANCELLED.toInt());
            erpOrderService.updateByMap(updateMap, orderId);
        }

        // 保存备注
        if (StringUtils.isNotBlank(remarks)){
            OrderRemarksEntity ore = new OrderRemarksEntity();
            ore.setOrOrderId(Long.valueOf(orderId));
            ore.setOrRemarks(remarks);
            ore.setOrCreateName(username);
            orderRemarksService.insert(ore);
        }

        erpOrderLogService.insertOrderLog(orderId,"订单作废");

        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R orderInfoFinish(String orderId, String remarks, String username) {
        OrderInfoEntity orderInfoEntity = this.selectById(orderId);
        if (StringUtils.equals(orderInfoEntity.getStatus(), OrderInfoStatusEnum.FINISH.toCode())){
            return R.error("订单已完成！");
        }
        if (!StringUtils.equals(orderInfoEntity.getPayStatus(), PayStatusEnum.ALREADY_PAY_1.toCode())){
            return R.error("订单未支付！");
        }

        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("status", OrderInfoStatusEnum.FINISH.toCode());
        updateMap.put("receivedStatus", ReceivedStatusEnum.RECEIVED.toInt());
        updateMap.put("receivedTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        this.baseMapper.updateByMap(orderId, updateMap);

        ErpOrderEntity erpOrder= erpOrderService.selectById(orderId);
        if (erpOrder != null){
            updateMap.remove("status");
            updateMap.put("productionStatus", ProductionStatusEnum.FINISH.toInt());
            erpOrderService.updateByMap(updateMap, orderId);
        }

        if (StringUtils.isNotBlank(remarks)){
            OrderRemarksEntity ore = new OrderRemarksEntity();
            ore.setOrOrderId(Long.valueOf(orderId));
            ore.setOrRemarks(remarks);
            ore.setOrCreateName(username);
            orderRemarksService.insert(ore);
        }

        erpOrderLogService.insertOrderLog(orderId,"订单完成");

        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R orderInfoDiscountAudit(String orderId, String discount, String remark, String username) {
        if (StringUtils.isBlank(orderId) || StringUtils.isBlank(discount) || StringUtils.isBlank(remark)){
            return R.error("请求参数有误！");
        }
        OrderInfoEntity orderInfoEntity = this.selectById(orderId);
        if (orderInfoEntity == null){
            return R.error("未查询到订单信息！");
        }
        if (StringUtils.equals(orderInfoEntity.getPayStatus(), PayStatusEnum.ALREADY_PAY_1.toCode())){
            return R.error("订单已支付！");
        }

        Map<String, Object> updateMap = new HashMap<>();
        // 现调价
        BigDecimal nowDiscount = new BigDecimal(discount);
        // 原调价
        BigDecimal oldDiscount = orderInfoEntity.getDiscount();
        // 原应付金额
        BigDecimal oldPayableAmount = orderInfoEntity.getPayableAmount();
        // 现应付金额
        BigDecimal nowPayableAmount = oldPayableAmount.subtract(oldDiscount).add(nowDiscount);
        int compare = nowPayableAmount.compareTo(BigDecimal.ZERO);
        if (compare < 0){
            return R.error("应付金额小于0，调价失败！");
        }else if (compare == 0){
            // 如果订单应付金额为0，订单支付状态改为已支付
            updateMap.put("payStatus", PayStatusEnum.ALREADY_PAY_1.toCode());
        }
        updateMap.put("discount", nowDiscount);
        updateMap.put("payableAmount", nowPayableAmount);
        this.baseMapper.updateByMap(orderId, updateMap);

        ErpOrderEntity erpOrder = erpOrderService.selectById(orderId);
        if (erpOrder != null){
            erpOrderService.updateByMap(updateMap, orderId);
        }

        OrderRemarksEntity orderRemarksEntity = new OrderRemarksEntity();
        orderRemarksEntity.setOrOrderId(Long.valueOf(orderInfoEntity.getOrderId()));
        orderRemarksEntity.setOrRemarks(remark);
        orderRemarksEntity.setOrCreateName(username);
        orderRemarksService.insert(orderRemarksEntity);

        erpOrderLogService.insertOrderLog(orderId,"订单调价，调价：" + nowDiscount + "，原调价：" + oldDiscount);

        return R.ok();
    }

    @Override
    public R orderinfoedit(String orderId) {
        // 返回结果
        Map<String, Object> result = new HashMap<>();
        /* 订单信息 */
        OrderInfoVo orderInfoVo = this.selectOrderInfoVoById(Long.valueOf(orderId));
        if (orderInfoVo == null){
            return R.error("未查询到订单信息");
        }
        result.put("orderInfo", orderInfoVo);

        /* ERP内部订单信息 */
        ErpOrderVo erpOrderVo = erpOrderService.selectErpOrderVoByOrderId(Long.valueOf(orderId));
        result.put("erpOrder", erpOrderVo);

        /* 商品信息 */
        List<OrderItemVo> orderItemVos = orderItemService.selectOrderItemVosById(Long.valueOf(orderId));
        result.put("orderItemList", orderItemVos);

        /* 支付信息 */
        UserPaymentEntity userPayment = userPaymentService.getPaySuccLastEntityByOrderId(orderId);
        result.put("userPayment", userPayment);

        /* 枚举信息 */
        result.put("goodsTypeEnum", JsonUtils.enumToList(GoodsTypeEnum.class));
        result.put("taxTypeEnum", JsonUtils.enumToList(TaxTypeEnum.class));

        /* 订单备注 */
        Map<String, Object> param = new HashMap<>();
        param.put("orderId", orderId);
        List<OrderRemarksVo> orderRemarksVos = orderRemarksService.selectOrderRemarksVosByMap(param);
        result.put("orderRemarks", orderRemarksVos);

        /* 订单日志 */
        param.clear();
        param.put("order_no", orderId);
        List<ErpOrderLogEntity> erpOrderLogEntities = erpOrderLogService.selectByMap(param);
        result.put("erpOrderLogs", erpOrderLogEntities);

        /* 支付信息 */
        Long parentOrderId = orderInfoVo.getParentOrderId();
        String relId = parentOrderId == null ? orderId : parentOrderId.toString();
        List<UserPaymentEntity> userPaymentEntities = userPaymentService.queryOrderPaymentInfo(relId);
        result.put("userPaymentList", userPaymentEntities);

        R ok = R.ok();
        ok.putAll(result);
        return ok;
    }

    @Override
    public R orderinfoaudit(String orderId) {
        if (StringUtils.isBlank(orderId)){
            return R.error("请求参数为空！");
        }
        // 查询参数
        Map<String, Object> param = new HashMap<>(1);
        // 返回结果
        Map<String, Object> result = new HashMap<>();

        /* 订单信息 */
        OrderInfoVo orderInfoVo = this.selectOrderInfoVoById(Long.valueOf(orderId));
        result.put("orderInfo", orderInfoVo);

        /* ERP内部订单信息 */
        ErpOrderVo erpOrderVo = erpOrderService.selectErpOrderVoByOrderId(Long.valueOf(orderId));
        result.put("erpOrder", erpOrderVo);

        /* 商品信息 */
        List<OrderItemVo> orderItemVos = orderItemService.selectOrderItemVosById(Long.valueOf(orderId));
        result.put("orderItemList", orderItemVos);

        /* 订单备注 */
        param.clear();
        param.put("orderId", orderId);
        List<OrderRemarksVo> orderRemarksVos = orderRemarksService.selectOrderRemarksVosByMap(param);
        result.put("orderRemarks", orderRemarksVos);

        /* 订单日志 */
        param.clear();
        param.put("order_no", orderId);
        List<ErpOrderLogEntity> erpOrderLogEntities = erpOrderLogService.selectByMap(param);
        result.put("erpOrderLogs", erpOrderLogEntities);

        /* 生产信息*/
        List<ErpOrderProductionEntity> erpOrderProductionEntityList = erpOrderProductionService.getErpOrderProductionEntity(orderId);
        result.put("erpOrderProductionEntityList", erpOrderProductionEntityList);

        /* 物流信息*/
        List<OrderLogisticsEntity> orderLogisticsEntityList = orderLogisticsService.selectList(new EntityWrapper<OrderLogisticsEntity>().eq("order_id", orderId).eq("`delete`",false));
        result.put("orderLogisticsEntityList", orderLogisticsEntityList);

        /* 订单相关枚举信息 */
        result.put("goodsTypeEnum", JsonUtils.enumToList(GoodsTypeEnum.class));
        result.put("taxTypeEnum", JsonUtils.enumToList(TaxTypeEnum.class));
        result.put("payTypeEnum", JsonUtils.enumToList(PayTypeEnum.class));

        /* 设计师信息 */
        param.clear();
        param.put("user_type", UserTypeEnum.DESIGNER.toCode());
        List<UserBaseInfoEntity> userBaseInfoEntities = userBaseInfoService.selectByMap(param);
        result.put("userBaseInfos", userBaseInfoEntities);

        /*  收款银行信息 */
        List<FinanceReceiptsAccountEntity> financeReceiptsAccountEntities = financeReceiptsAccountService.selectList(null);
        result.put("receiptsAccounts", financeReceiptsAccountEntities);

        /* 支付信息 */
        UserPaymentEntity userPayment = userPaymentService.getPaySuccLastEntityByOrderId(orderId);
        result.put("userPayment", userPayment);

        /* 当前登陆人信息 */
        result.put("username", UserUtils.getCurentUser().getUsername());

        /* 支付信息 */
        Long parentOrderId = orderInfoVo.getParentOrderId();
        String relId = parentOrderId == null ? orderId : parentOrderId.toString();
        List<UserPaymentEntity> userPaymentEntities = userPaymentService.queryOrderPaymentInfo(relId);
        result.put("userPaymentList", userPaymentEntities);

        R ok = R.ok();
        ok.putAll(result);
        return ok;
    }

    @Override
    public R queryOrderInfo(Long orderId) {
        // 返回结果
        Map<String, Object> result = new HashMap<>();
        /* 订单信息 */
        OrderInfoVo orderInfoVo = this.selectOrderInfoVoById(orderId);
        result.put("orderInfo", orderInfoVo);
        /* 商品信息 */
        List<OrderItemVo> orderItemVos = orderItemService.selectOrderItemVosById(orderId);
        result.put("orderItemList", orderItemVos);
        /* 支付信息 */
        Long parentOrderId = orderInfoVo.getParentOrderId();
        String relId = parentOrderId == null ? orderId.toString() : parentOrderId.toString();
        List<UserPaymentEntity> userPaymentEntities = userPaymentService.queryOrderPaymentInfo(relId);
        result.put("userPaymentList", userPaymentEntities);
        /* 订单相关枚举信息 */
        result.put("goodsTypeEnum", JsonUtils.enumToList(GoodsTypeEnum.class));
        result.put("taxTypeEnum", JsonUtils.enumToList(TaxTypeEnum.class));
        result.put("payTypeEnum", JsonUtils.enumToList(PayTypeEnum.class));
        /*  收款银行信息 */
        List<FinanceReceiptsAccountEntity> financeReceiptsAccountEntities = financeReceiptsAccountService.selectList(null);
        result.put("receiptsAccounts", financeReceiptsAccountEntities);

        R ok = R.ok();
        ok.putAll(result);
        return ok;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R orderTax(String orderId, Integer sendTax) {
        ErpOrderEntity erpOrderEntity = erpOrderService.selectById(orderId);
        if (erpOrderEntity == null){
            OrderInfoEntity orderInfoEntity = this.selectById(orderId);
            erpOrderEntity = ErpOrderUtils.ziyunOrderToErp(orderInfoEntity);
            erpOrderEntity.setSendTax(sendTax);
            erpOrderService.insert(erpOrderEntity);

            List<OrderItemEntity> orderItemEntityList = orderItemService.selectByOrderId(Long.valueOf(orderId));
            List<ErpOrderItemEntity> erpOrderItemEntityList = ErpOrderUtils.ziyunOrderItemToErp(orderItemEntityList, orderId);
            erpOrderItemService.insertBatch(erpOrderItemEntityList);
        }else {
            Map<String, Object> updateMap = new HashMap<>();
            updateMap.put("sendTax", sendTax);
            erpOrderService.updateByMap(updateMap, orderId);
        }

        String msg = sendTax == 0 ? "否" : "是";
        erpOrderLogService.insertOrderLog(orderId,"订单送货单是否开发票：" + msg);

        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R orderPayment(OrderPaymentDto orderPaymentDto) {
        String orderId = orderPaymentDto.getOrderId();
        OrderInfoEntity orderInfo = this.selectById(orderId);
        String payStatus = orderInfo.getPayStatus();
        if (StringUtils.equals(PayStatusEnum.ALREADY_PAY_1.toCode(), payStatus)){
            return R.error("订单已支付！");
        }
        if (!StringUtils.equals(PayStatusEnum.NOT_PAY_0.toCode(), payStatus)
                && !StringUtils.equals(PayStatusEnum.PAY_PART_3.toCode(), payStatus)){
            return R.error("订单支付状态异常！");
        }
        // 查询订单是否有支付成功记录
        if (StringUtils.equals(PayStatusEnum.NOT_PAY_0.toCode(), payStatus)){
            UserPaymentEntity userPaymentEntity = userPaymentService.getPaySuccLastEntityByOrderId(orderId);
            if (userPaymentEntity != null){
                return R.error("订单支付状态异常！");
            }
        }

        // 支付方式（线上/线下）
        if (orderPaymentDto.getPayAppId().startsWith(PayTypeWayEnum.PAY_OFFLINE.toCode())){
            orderPaymentDto.setPayType(PayTypeWayEnum.PAY_OFFLINE.toCode());
        }else {
            orderPaymentDto.setPayType(PayTypeWayEnum.PAY_ONLINE.toCode());
        }

        /* 更新订单信息 */
        Map<String, Object> orderUpdateMap = new HashMap<>();
        BigDecimal payed = orderInfo.getPayed().add(orderPaymentDto.getMoney());
        int compare = payed.compareTo(orderInfo.getPayableAmount());
        if (compare < 0){// 部分付款
            orderUpdateMap.put("payStatus", PayStatusEnum.PAY_PART_3.toCode());
        }else if (compare == 0){// 付清
            /*
             *  大纸订单、复印纸订单，如果付款方式是 线下付款，则状态 变为 PAY_OFFLINE_7(7,"线下已支付"),
             *  付款类型为转账付款transfer(8,"transfer","转账付款"),则状态变为 TRANSFER_8(8,"已支付待审核(转账)"),
             *  其他 状态变为 ALREADY_PAY_1(1,"已支付")
             * */
            String promotionType = orderInfo.getPromotionType();
            if (StringUtils.equals(promotionType, PromotionTypeEnum.PAPER.toCode()) || StringUtils.equals(promotionType, PromotionTypeEnum.COPY.toCode())){
                if (StringUtils.equals(orderPaymentDto.getPayType(), PayTypeWayEnum.PAY_OFFLINE.toCode())){
                    orderUpdateMap.put("payStatus", PayStatusEnum.PAY_OFFLINE_7.toCode());
                }else if (StringUtils.equals(orderPaymentDto.getPayAppId(), PayTypeEnum.TRANSFER.toCode())){
                    orderUpdateMap.put("payStatus", PayStatusEnum.TRANSFER_8.toCode());
                }else {
                    orderUpdateMap.put("payStatus", PayStatusEnum.ALREADY_PAY_1.toCode());
                }
            }else {
                orderUpdateMap.put("payStatus", PayStatusEnum.ALREADY_PAY_1.toCode());
            }
        }else {// 付款超出订单金额
            return R.error("已付款金额超出订单应付总额！");
        }
        orderUpdateMap.put("payed", payed);
        baseMapper.updateByMap(orderId, orderUpdateMap);
        ErpOrderEntity erpOrder = erpOrderService.selectById(orderId);
        if (erpOrder != null){
            orderUpdateMap.put("paymentTime", DateUtils.format(orderPaymentDto.getPaymentTime(), "yyyy-MM-dd HH:mm:ss"));
            orderUpdateMap.put("payment", orderPaymentDto.getPayName());
            erpOrderService.updateByMap(orderUpdateMap, orderId);
        }

        /* 新增用户支付记录表信息 */
        UserPaymentEntity userPayment = new UserPaymentEntity();
        userPayment.setAccount(orderPaymentDto.getAccount());
        userPayment.setBank(orderPaymentDto.getBank());
        userPayment.setPayName(orderPaymentDto.getPayName());
        userPayment.setMoney(orderPaymentDto.getMoney());
        userPayment.setPayType(orderPaymentDto.getPayType());
        userPayment.setMemo(orderPaymentDto.getMemo());
        userPayment.setPayAppId(orderPaymentDto.getPayAppId());
        userPayment.setTPayed(orderPaymentDto.getPaymentTime());
        String paymentsId = UserPaymentUtils.getPaymentsId();
        boolean repeat = true;
        do {
            UserPaymentEntity upe = userPaymentService.selectById(paymentsId);
            if (upe == null){
                repeat = false;
            }
        }while (repeat);
        userPayment.setPaymentId(paymentsId);
        userPayment.setUserId(orderInfo.getUserId().toString());
        userPayment.setStatus(UserPaymentStatusEnum.SUCC.toCode());
        userPayment.setCurMoney(userPayment.getMoney());

        // 获取当前登陆用户ID
        Long userId = UserUtils.getCurentUser().getUserId();
        userPayment.setOpId(userId.toString());

        /* 新增用户支付关联表信息 */
        UserPaymentBillEntity userPaymentBill = new UserPaymentBillEntity();
        userPaymentBill.setRelId(Long.valueOf(orderId));
        userPaymentBill.setBillType(BillTypeEnum.PAYMENTS.toCode());
        userPaymentBill.setPayObject(PayObjectEnum.ORDER.toCode());
        userPaymentBill.setBillId(userPayment.getPaymentId());
        userPaymentBill.setMoney(userPayment.getMoney());
        // 新增用户支付记录表信息
        userPaymentService.insert(userPayment);
        // 新增用户支付关联表信息
        userPaymentBillService.insert(userPaymentBill);

        erpOrderLogService.insertOrderLog(orderId, "订单支付");

        return R.ok();
    }

    @Override
    public R querySellerOrderInfo(Long orderId) {
        Map<String, Object> result = new HashMap<>();

        /* 订单信息 */
        OrderInfoVo orderInfoVo = this.selectOrderInfoVoById(orderId);
        result.put("orderInfo", orderInfoVo);

        /* 商品信息 */
        List<OrderItemVo> orderItemVos = orderItemService.selectOrderItemVosById(orderId);
        result.put("orderItemList", orderItemVos);

        /* 本厂制作工序及整个商品工序制作进度*/
        ErpOrderProductionEntity erpOrderProduction = erpOrderProductionService.selectOne(new EntityWrapper<>(new ErpOrderProductionEntity())
                .eq("production_order", orderId)
                .eq("allot_type", "procedure")
        );
        if (erpOrderProduction != null){
            String partsName = erpOrderProduction.getPartsName();
            String attributeName = erpOrderProduction.getAttributeName();
            result.put("procedure", partsName + "："+ attributeName);
        }

        /* 物流信息*/
        List<OrderLogisticsEntity> orderLogisticsEntityList = orderLogisticsService.selectList(new EntityWrapper<OrderLogisticsEntity>()
                .eq("order_id", orderId).eq("`delete`",false)
        );
        result.put("orderLogisticsEntityList", orderLogisticsEntityList);

        /* 订单相关枚举信息 */
        result.put("goodsTypeEnum", JsonUtils.enumToList(GoodsTypeEnum.class));
        result.put("taxTypeEnum", JsonUtils.enumToList(TaxTypeEnum.class));
        result.put("payTypeEnum", JsonUtils.enumToList(PayTypeEnum.class));

        /* 支付信息 */
        Long parentOrderId = orderInfoVo.getParentOrderId();
        String relId = parentOrderId == null ? orderId.toString() : parentOrderId.toString();
        List<UserPaymentEntity> userPaymentEntities = userPaymentService.queryOrderPaymentInfo(relId);
        result.put("userPaymentList", userPaymentEntities);

        R ok = R.ok();
        ok.putAll(result);
        return ok;
    }

    @Override
    public R paperOrderInfo(Long orderId) {
        /* 订单信息 */
        OrderInfoVo orderInfoVo = this.selectOrderInfoVoById(orderId);
        /* ERP内部订单信息 */
        ErpOrderVo erpOrderVo = erpOrderService.selectErpOrderVoByOrderId(Long.valueOf(orderId));
        /* 商品信息 */
        List<OrderItemVo> orderItemList = orderItemService.selectOrderItemVosById(Long.valueOf(orderId));
        /* 订单发票类型 */
        List<Map<String, Object>> taxTypeEnum = JsonUtils.enumToList(TaxTypeEnum.class);
        /* 第三方类型 */
        List<Map<String, Object>> thirdMerchantTypeEnum = JsonUtils.enumToList(ThirdMerchantTypeEnum.class);
        /* 商品类型 */
        List<Map<String, Object>> goodsTypeEnum = JsonUtils.enumToList(GoodsTypeEnum.class);
        /* 收款银行信息 */
        List<FinanceReceiptsAccountEntity> financeReceiptsAccountEntities = financeReceiptsAccountService.selectList(null);
        /* 支付信息 */
        UserPaymentEntity userPayment = userPaymentService.getPaySuccLastEntityByOrderId(orderId.toString());
        /* 登陆人 */
        String username = UserUtils.getCurentUser().getUsername();
        /* 支付信息 */
        Long parentOrderId = orderInfoVo.getParentOrderId();
        String relId = parentOrderId == null ? orderId.toString() : parentOrderId.toString();
        List<UserPaymentEntity> userPaymentEntities = userPaymentService.queryOrderPaymentInfo(relId);

        return R.ok().put("paperOrderInfo", orderInfoVo)
                .put("erpOrder", erpOrderVo)
                .put("orderItemList",orderItemList)
                .put("taxTypeEnum", taxTypeEnum)
                .put("thirdMerchantTypeEnum", thirdMerchantTypeEnum)
                .put("goodsTypeEnum", goodsTypeEnum)
                .put("receiptsAccounts", financeReceiptsAccountEntities)
                .put("userPayment", userPayment)
                .put("username", username)
                .put("userPaymentList", userPaymentEntities);
    }

    @Override
    public PageUtils getAllOrderInfo(Map<String, Object> params, Integer userId) {
        Page<OrderInfoEntity> page = new Page<>();
        page.setCurrent(Integer.valueOf(params.get("page").toString()));
        page.setSize(Integer.valueOf(params.get("limit").toString()));
        List<OrderInfoEntity> list = this.baseMapper.getAllOrder(page, userId);
        page.setRecords(list);
        return new PageUtils(page);
    }

    @Override
    public Page<OrderInfoEntity> selecOrderPayConfirmPage(Page<OrderInfoEntity> page) {
        List<OrderInfoEntity> orderInfoEntityList = this.baseMapper.selecOrderPayConfirmPage(page);
        return page.setRecords(orderInfoEntityList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void adnormal(String orderId) {
        OrderInfoEntity orderInfoEntity = this.baseMapper.selectById(orderId);
        ErpOrderEntity erpOrder = erpOrderService.selectByNo(orderId);

        if(erpOrder != null){
            if(erpOrder.getProductionStatus() == ProductionStatusEnum.ABNORMAL.toInt()){
                return;
            }

            Map<String,Object> updateMap = new HashMap<>();
            updateMap.put("productionStatus", ProductionStatusEnum.ABNORMAL.toInt());
            erpOrderService.updateByMap(updateMap,erpOrder.getOrderNo());
        }else{
            erpOrder = ErpOrderUtils.ziyunOrderToErp(orderInfoEntity);
            erpOrder.setProductionStatus(ProductionStatusEnum.ABNORMAL.toInt());

            List<OrderItemEntity> orderItemEntityList = orderItemService.selectByOrderId(Long.parseLong(orderId));
            List<ErpOrderItemEntity> erpOrderItemEntityList = ErpOrderUtils.ziyunOrderItemToErp(orderItemEntityList,orderId);

            erpOrderService.insert(erpOrder);
            erpOrderItemService.insertBatch(erpOrderItemEntityList);
        }
        erpOrderLogService.insertOrderLog(orderId,"订单标记异常");
    }


    @Override
    public void confirmOrderPayTask(List<OrderInfoEntity> list) {
        for(OrderInfoEntity orderInfoEntity: list){
            ErpOrderEntity erpOrderEntity = erpOrderService.selectByNo(orderInfoEntity.getOrderId());
            if(erpOrderEntity == null){
                logger.error("计划任务：财务自动确认付款（支付宝、微信），订单号："+orderInfoEntity.getOrderId()+" ,未找到 erp_order 生产表信息");
//                mailService.sendSysErrorMail("计划任务：财务自动确认付款（支付宝、微信），订单号："+orderInfoEntity.getOrderId()+" ,未找到 erp_order 生产表信息");
                continue;
            }

            // 查询支付金额
            BigDecimal totalPayed = userPaymentBillService.getTotalPayed(orderInfoEntity.getOrderId());
            Map<String,Object> updateMap = new HashMap<>();
            updateMap.put("receiveMoney",totalPayed);
            updateMap.put("receiveMoneyDate",DateUtils.format(new Date()));
            updateMap.put("receiveMoneyRemark","系统自动确认付款");
            boolean succ = false;
            try {
                erpOrderService.updateByMap(updateMap,erpOrderEntity.getOrderNo());
                succ = true;
            }catch (Exception e){
                logger.error("计划任务：财务自动确认付款（支付宝、微信），订单号："+orderInfoEntity.getOrderId()+" , 收款失败：" + e.getMessage());
//                mailService.sendSysErrorMail("计划任务：财务自动确认付款（支付宝、微信），订单号："+orderInfoEntity.getOrderId()+" , 收款失败：" + e.getMessage());
                e.printStackTrace();
            }
            if (succ){
                erpOrderLogService.insertOrderLog(erpOrderEntity.getOrderNo(),"系统自动确认付款");
            }
        }
    }

    @Override
    public List<Map<String, Object>> memberSyncTwb() {
        return this.baseMapper.memberSyncTwb();
    }

    @Override
    @Transactional
    public R orderQuickInvalid(String orderId, String remarks, String username) {
        // 若有生产信息，不能直接作废，提示先取消生产单
        ErpOrderProductionEntity erpOrderProduction = new ErpOrderProductionEntity();
        int selectCount = erpOrderProductionService.selectCount(new EntityWrapper<>(erpOrderProduction)
                .eq("order_no", orderId)
                .eq("del", DeleteEnum.NOT_DELETE.toInt())
                .ne("production_status", OrderProductionStatusEnum.CANCLE.toInt())
        );
        if (selectCount > 0){
            return R.error("存在活动生产单");
        }

        Map<String, Object> orderMap = New.hashMap();
        orderMap.put("status", OrderInfoStatusEnum.DEAD.toCode());
        this.updateByMap(orderMap, orderId);
        ErpOrderEntity erpOrder = erpOrderService.selectById(orderId);
        if (erpOrder != null){
            Map<String, Object> erpOrderMap = New.hashMap();
            erpOrderMap.put("productionStatus", ProductionStatusEnum.CANCELLED.toInt());
            erpOrderService.updateByMap(erpOrderMap, orderId);
        }

        OrderInfoEntity orderInfo = this.selectById(orderId);
        Integer userId = orderInfo.getUserId();
        List<UserPaymentEntity> userPaymentList = userPaymentService.queryOrderPaymentInfo(orderId);
        Map<String, Object> paymentMap = New.hashMap();
        Map<String, Object> walletMap = New.hashMap();
        for (UserPaymentEntity userPayment : userPaymentList){
            String paymentId = userPayment.getPaymentId();
            paymentMap.put("status", UserPaymentStatusEnum.CANCEL.toCode());
            userPaymentService.updateByMap(paymentMap, paymentId);

            BigDecimal money = userPayment.getMoney();
            String payAppId = userPayment.getPayAppId();
            if ("credit".equals(payAppId)){ // 信用支付
                UserWalletEntity userWallet = userWalletService.selectById(userId);
                BigDecimal creditUse = userWallet.getCreditUse();
                creditUse = creditUse.add(money);
                walletMap.put("creditUse", creditUse);
                userWalletService.updateByMap(walletMap, userId);

                UserCreditEntity userCredit = new UserCreditEntity();
                userCredit.setUserId(userId);
                userCredit.setMoney(money);
                userCredit.setMessage("订单作废，返还信用额度");
                userCredit.setMtime(new Date());
                userCredit.setPaymentId(paymentId);
                userCredit.setOrderId(Long.valueOf(orderId));
                userCredit.setMemo("后台人员操作");
                userCredit.setCreditUse(creditUse);
                usercreditService.insert(userCredit);
            }else if ("deposit".equals(payAppId)){ // 预存款支付

            }else if ("scholarship".equals(payAppId)){ // 奖励金支付

            }else { // 其他支付（暂不考虑优惠卷使用情况）

            }
        }

        // 保存备注信息
        if (StringUtils.isNotBlank(remarks)){
            OrderRemarksEntity ore = new OrderRemarksEntity();
            ore.setOrOrderId(Long.valueOf(orderId));
            ore.setOrRemarks(remarks);
            ore.setOrCreateName(username);
            orderRemarksService.insert(ore);
        }

        erpOrderLogService.insertOrderLog(orderId,"后台快捷作废订单");
        return R.ok();
    }

    @Override
    public R getOrderLog(Long orderId) {
        Map<String, Object> result = new HashMap<>();
        /* 客服、跟单员信息 */
        OrderServicerVo orderServicerVo = this.baseMapper.selectOrderServicer(orderId);
        result.put("orderServicer", orderServicerVo);
        /* 订单备注 */
        Map<String, Object> param = new HashMap<>(1);
        param.put("orderId", orderId);
        List<OrderRemarksVo> orderRemarksVos = orderRemarksService.selectOrderRemarksVosByMap(param);
        result.put("orderRemarks", orderRemarksVos);
        /* 订单日志 */
        param.clear();
        param.put("order_no", orderId);
        List<ErpOrderLogEntity> erpOrderLogEntities = erpOrderLogService.selectByMap(param);
        result.put("erpOrderLogs", erpOrderLogEntities);
        List<OrderLogVo> orderLogs = orderLogService.selectByOrderId(orderId);
        result.put("orderLogs", orderLogs);

        R ok = R.ok();
        ok.putAll(result);
        return ok;
    }

    @Override
    public R getOrderProduction(Long orderId) {
        Map<String, Object> result = new HashMap<>();
        List<ErpOrderProductionEntity> erpOrderProductionEntityList = erpOrderProductionService.getErpOrderProductionEntity(orderId.toString());
        result.put("erpOrderProductionEntityList", erpOrderProductionEntityList);
        R ok = R.ok();
        ok.putAll(result);
        return ok;
    }

    @Override
    public R getOrderLogi(Long orderId) {
        Map<String, Object> result = new HashMap<>();
        List<OrderLogisticsEntity> orderLogisticsEntityList = orderLogisticsService.selectList(new EntityWrapper<OrderLogisticsEntity>()
                .eq("order_id", orderId).eq("`delete`",false)
        );
        result.put("orderLogisticsEntityList", orderLogisticsEntityList);
        R ok = R.ok();
        ok.putAll(result);
        return ok;
    }

    @Override
    public R getOrderDesigner(Map<String, Object> map) {
        String name = (String) map.get("name");
        Map<String, Object> result = new HashMap<>();
        List<UserBaseInfoEntity> userBaseInfoEntities = userBaseInfoService.selectList(new EntityWrapper<>(new UserBaseInfoEntity())
                .eq("user_type", UserTypeEnum.DESIGNER.toCode())
                .like("name", name)
                .last("limit 20")
        );
        result.put("userBaseInfos", userBaseInfoEntities);
        R ok = R.ok();
        ok.putAll(result);
        return ok;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveDesinOrderLogisticsInfo(ErpLogisticsDto erpLogisticsDto, String username) {
        ErpLogisticsEntity erpLogistics = erpLogisticsDto.getErpLogisticsEntity();
        Long orderId = erpLogistics.getOrderId();
        ErpOrderEntity erpOrder = erpOrderService.selectById(orderId);
        if (erpOrder == null || erpOrder.getProductionStatus() == ProductionStatusEnum.UN_AUDITED.toInt()){
            return R.error("订单未审核");
        }

        // 添加物流信息
        erpLogistics.setCreateName(username);
        erpLogistics.setSendTime(new Date());
        erpLogisticsService.insert(erpLogistics);
        List<ErpLogisticsItemEntity> erpLogisticsItemList = erpLogisticsDto.getErpLogisticsItemList();
        int itemListSize = erpLogisticsItemList.size();
        if (itemListSize > 0){
            erpLogisticsItemService.saveBatchByLogisticsId(erpLogisticsItemList, erpLogistics.getLogiId());
        }

        erpOrderLogService.insertOrderLog(orderId.toString(),"设计商品添加物流");

        return R.ok();
    }

}
